'''
@Author: your name
@Date: 2019-06-24 11:32:40
LastEditTime: 2021-11-12 10:36:32
LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /tinyms/tinyms-api/apps/cms/link/views.py
'''
from crypt import methods
from flask import render_template,request,jsonify
from app import db,auth
from . import cms_link
from .model import Link
from .service import LinkService
import json
import uuid
from apps.utils import auty

'''
保存或更新数据
'''
@cms_link.route('/saveOrUpdate',methods=['GET','POST'])
def saveOrUpdate():
    data = {}
    if request.method == "POST":
        for key in request.form:
            data[key] = request.form.get(key)
    else:
        for key in request.args:
            data[key] = request.args.get(key)
    link = Link()
    link.link_title = data['link_title']
    link.link_images = data['link_images']
    link.link_address = data['link_address']
    link.link_remarks = data['link_remarks']
    if not data['link_pk']:
            # article.article_pk = str(uuid.uuid1())
        LinkService.save(link)
    else:
        link.link_pk=data['link_pk']
        LinkService.update(link)
    data = {
        'code':'0',
        'msg':'添加成功'
    }
    return json.dumps(data)


# 进行分页查询
@cms_link.route('/pages',methods=['GET','POST'])
@auty.login_required #必须登录的装饰器校验
def pages():
    if request.method == "POST":
        page = request.form.get("page") #获取页码
    else:
        page = request.args.get("page")
    pages = LinkService.pages(page)
    # db.session.close()
    #将分页对象组装为需要的数据
    data = {
        'msg':'success',
        'code':0,
        'data':Link.to_dict(pages.items),
        'count':pages.total
    }
    print(pages.items)
    return json.dumps(data,ensure_ascii=False)
    # return jsonify(data)

'''
通过主键删除数据
'''
@cms_link.route('/delete',methods={'POST','GET'})
@auty.login_required #必须登录的装饰器校验
def delete():
    if request.method == "POST":
        link_pk = request.form.get("link_pk") #获取页码
    else:
        link_pk = request.args.get("link_pk")
    LinkService.delete(link_pk)
    data = {
        'msg':'success',
        'code':0,
        'data':""
    }
    return json.dumps(data)







